const { createRegisterError } = require("../consitant/err.type");
const { createUser, getUserInfo,getUsers } = require("../service/user.service");
const {JWT_SECRET} = require('../config/config.default');
const jwt = require('jsonwebtoken')
const {getRoleInfo} = require("../service/role.service")
class UserController{
  async register(ctx,next){
    try{
      console.log(ctx.request.body)
      const {user_name,password,role_id} = ctx.request.body;
      const user_res = await createUser(user_name,password,role_id)
      ctx.body = {
        code:0,
        message:'注册成功',
        result:user_res
      }
    }catch(err){
      console.log(err);
      ctx.app.emit('error',createRegisterError,ctx)
    }
  }
  async login(ctx,next){
    const {user_name} = ctx.request.body;
    try{
      const res = await getUserInfo({user_name});
      console.log(res)
      const {password,...resUser} = res;
      ctx.body = {
        code:'0',
        message:'登录成功',
        result:{
          token:jwt.sign(resUser,JWT_SECRET,{expiresIn:'1d'})
        }
      }
    }catch(err){
      console.error(err)
    }

  }
  async getinfo(ctx,next) {
    try{
      const {id} = ctx.state.user;
      const res = await getUserInfo({id})
      const role = await getRoleInfo(res.role_id)
      console.log(role)
      ctx.body = {
        code:'0',
        message:'查询成功',
        result:Object.assign(res,role)
      }
    }catch (err) {
      console.error(err)
    }

  }
  async getUserController(ctx,next) {
    try {
      console.log(ctx.request.query)
      const {limit,page} = ctx.request.query
      const res = await getUsers(limit,page)
      ctx.body = {
        code:"0",
        message:"查询成功",
        result:res
      }

  }catch (err) {
      console.error(err)
    }}
}
module.exports = new UserController();
